package com.resume.aipeople.service.ai;

import ai.z.openapi.ZhipuAiClient;
import ai.z.openapi.service.model.ChatCompletionResponse;
import ai.z.openapi.service.model.ChatMessage;
import ai.z.openapi.service.model.ChatMessageRole;
import com.resume.aipeople.service.ai.model.LLMModelManager;
import com.resume.aipeople.service.ai.model.LLMModelStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Arrays;

@Service
@RequiredArgsConstructor
@Slf4j
public class LLMService {

    @Value("${zai.api.key:${ZAI_API_KEY:}}")
    private String zaiApiKey;
    
    private final LLMModelManager modelManager;

    public Mono<String> generateResponse(String systemPrompt, String userMessage, String characterName) {
        return Mono.fromCallable(() -> {
            LLMModelStrategy currentStrategy = modelManager.getCurrentModelStrategy();
            log.info("开始LLM调用 - 模型: {}, 角色: {}, 用户消息长度: {}", 
                    currentStrategy.getDisplayName(), characterName, userMessage.length());
            
            // 构建消息列表
            var messages = Arrays.asList(
                    ChatMessage.builder().role(ChatMessageRole.SYSTEM.value()).content(systemPrompt).build(),
                    ChatMessage.builder().role(ChatMessageRole.USER.value()).content(userMessage).build()
            );
            
            // 根据模型类型选择不同的处理方式
            if (currentStrategy.getModelName().startsWith("gemini")) {
                // Gemini模型直接处理
                return messages;
            } else {
                // GLM模型使用原有逻辑
                if (zaiApiKey == null || zaiApiKey.trim().isEmpty()) {
                    log.error("ZAI API Key 未配置");
                    throw new RuntimeException("API Key 未配置");
                }
                
                ZhipuAiClient client = ZhipuAiClient.builder()
                        .apiKey(zaiApiKey)
                        .build();
                
                var request = currentStrategy.buildRequest(messages, 0.8f, 200);
                
                log.info("发送GLM请求 - 模型: {}, 消息数: {}, 用户消息: {}", 
                        currentStrategy.getDisplayName(), request.getMessages().size(), userMessage);
                ChatCompletionResponse response = client.chat().createChatCompletion(request);
                
                log.info("GLM响应 - 成功: {}, 消息: {}", response.isSuccess(), response.getMsg());
                
                if (response.isSuccess()
                        && response.getData() != null
                        && response.getData().getChoices() != null
                        && !response.getData().getChoices().isEmpty()
                        && response.getData().getChoices().get(0).getMessage() != null) {
                    Object content = response.getData().getChoices().get(0).getMessage().getContent();
                    return content;
                }
                log.warn("GLM返回非成功响应: {}", response.getMsg());
                return "抱歉，我现在无法回应。";
            }
        })
        .flatMap(content -> {
            LLMModelStrategy currentStrategy = modelManager.getCurrentModelStrategy();
            return currentStrategy.processResponse(content);
        })
        .timeout(java.time.Duration.ofSeconds(15)) // 添加15秒超时
        .doOnError(error -> log.error("LLM调用异常: {}", error.getMessage(), error))
        .onErrorReturn("抱歉，我现在遇到了一些技术问题，请稍后再试。");
    }

    public Mono<String> generateResponseWithSkill(String systemPrompt, String userMessage,
                                                  String characterName, String skill) {
        String enhancedPrompt = enhancePromptWithSkill(systemPrompt, skill);
        return generateResponse(enhancedPrompt, userMessage, characterName);
    }

    private String enhancePromptWithSkill(String basePrompt, String skill) {
        // 极简化的角色扮演指导，大幅减少token消耗
        String roleplayGuideline = "\n\n【要求】保持角色身份，回复简洁(10-30字)。";
        
        switch (skill) {
            case "knowledge":
                return basePrompt + roleplayGuideline + "知识问答。";
            case "emotion":
                return basePrompt + roleplayGuideline + "情感回应。";
            case "creative":
                return basePrompt + roleplayGuideline + "创意表达。";
            case "memory":
                return basePrompt + roleplayGuideline + "记忆对话。";
            case "analyze":
                return basePrompt + roleplayGuideline + "分析思考。";
            default:
                return basePrompt + roleplayGuideline;
        }
    }
    
    /**
     * 获取当前模型显示名称
     * @return 当前模型显示名称
     */
    public String getCurrentModelDisplayName() {
        return modelManager.getCurrentModelDisplayName();
    }
    
    /**
     * 切换模型
     * @param modelName 模型名称
     * @return 是否切换成功
     */
    public boolean switchModel(String modelName) {
        return modelManager.switchModel(modelName);
    }
    
    /**
     * 获取所有可用模型
     * @return 所有可用模型列表
     */
    public java.util.List<LLMModelManager.LLMModelInfo> getAvailableModels() {
        return modelManager.getAvailableModels();
    }
}